package com.smh;

import org.junit.jupiter.api.Test;

import java.util.Arrays;

/**
 * @author shiminghui
 * @date 2025/3/16 18:59
 * @description: TODO
 */
public class _057_零钱兑换问题 {
    @Test
    public void test01() {
        int[] coins = {1, 2, 5};
        System.out.println(coinChange(coins, 11));
    }

    /**
     * 零钱兑换问题,获取最少的硬币数
     *
     * @param coins
     * @param amount
     * @return
     */
    public int coinChange(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, amount + 1);
        dp[0] = 0;
        for (int coin : coins) {
            for (int j = 0; j <= amount; j++) {
                if (j >= coin) {
                    dp[j] = Math.min(dp[j], dp[j - coin] + 1);
                }
            }
            System.out.println(Arrays.toString(dp));
        }
        return dp[amount] == amount + 1 ? -1 : dp[amount];
    }

    /**
     * 零钱兑换问题,获取总兑换种数
     * 0       1       2       3       4       5  // 总金额
     * 1    -       1       11      111     1111    11111
     * <p>
     * 2    -       1       11      111     1111    11111
     * 2       21      211     2111
     * 22      221
     * <p>
     * 5    -       1       11      111     1111    11111
     * 2       21      211     2111
     * 221
     * 5
     *
     * @param coins
     * @param amount
     * @return
     */
    public int coinChange2(int[] coins, int amount) {
        int[][] dp = new int[coins.length][amount + 1];

        for (int i = 0; i < coins.length; i++) {
            dp[i][0] = 1;
        }


        for (int i = 0; i < coins.length; i++) {
            for (int j = 0; j <= amount; j++) {
                if (i == 0) {
                    if (j % coins[i] == 0) {
                        dp[i][j] = 1;
                    }
                } else {
                    if (j >= coins[i]) {
                        dp[i][j] = dp[i - 1][j] + dp[i][j - coins[i]];
                    } else {
                        dp[i][j] = dp[i - 1][j];
                    }
                }
            }
        }
        return dp[coins.length - 1][amount];
    }

    /**
     * 降维
     *
     * @param coins
     * @param amount
     * @return
     */
    public int coinChange3(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        dp[0] = 1;
        for (int i = 0; i < coins.length; i++) {
            for (int j = coins[i]; j <= amount; j++) {
                if (i == 0) {
                    if (j % coins[i] == 0) {
                        dp[j] = 1;
                    }
                } else {
                    if (j >= coins[i]) {
                        dp[j] = dp[j] + dp[j - coins[i]];
                    }
                }
            }
        }
        return dp[amount];
    }
}
